package com.carleasoft.mps.qa.business.anwser.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.IBeanUtil;
import com.carleasoft.mps.core.utils.IpUtils;
import com.carleasoft.mps.qa.business.anwser.bean.entity.*;
import com.carleasoft.mps.qa.business.anwser.bean.po.NairePagePo;
import com.carleasoft.mps.qa.business.anwser.bean.po.PageAnswerPo;
import com.carleasoft.mps.qa.business.anwser.bean.vo.AnswerPageQueryVo;
import com.carleasoft.mps.qa.business.anwser.bean.vo.PageAnswerVo;
import com.carleasoft.mps.qa.business.anwser.bean.vo.ScoreCountVo;
import com.carleasoft.mps.qa.business.anwser.bean.vo.UserInfoVo;
import com.carleasoft.mps.qa.business.anwser.dao.NaireMapper;
import com.carleasoft.mps.qa.business.anwser.service.*;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: yangHao
 * @createDate:2023/5/24
 * @description:
 */
@Service
public class NaireServiceImpl extends ServiceImpl<NaireMapper, NaireEntity> implements NaireService {
    @Autowired
    private NaireRecordService naireRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveNaire(NaireEntity naireEntity) {
        boolean isOk = false;
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        if (StrUtil.isNotBlank(naireEntity.getNaireCode())) {
            //编辑
            NaireEntity entity = this.getOne(Wrappers.<NaireEntity>lambdaQuery().eq(NaireEntity::getNaireCode, naireEntity.getNaireCode()));
            BeanUtil.copyProperties(naireEntity, entity);
            entity.setUpdatePersonCode(user.getUserCode());
            entity.setUpdatePersonName(user.getUserName());
            entity.setUpdateTime(LocalDateTime.now());
            isOk = this.updateById(entity);
        } else {
            naireEntity.setNaireCode(IdWorker.getIdStr());
            naireEntity.setCreateTime(LocalDateTime.now());
            naireEntity.setCreatePersonCode(user.getUserCode());
            naireEntity.setCreatePersonName(user.getUserName());
            naireEntity.setUpdatePersonCode(user.getUserCode());
            naireEntity.setUpdatePersonName(user.getUserName());
            naireEntity.setUpdateTime(LocalDateTime.now());
            isOk = this.save(naireEntity);
        }
        return isOk;
    }

    @Override
    public Page<NaireEntity> pageQuery(Page page, NairePagePo nairePagePo) {
        QueryWrapper<NaireEntity> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(nairePagePo.getNaireName())) {
            queryWrapper.like("NAIRE_NAME", nairePagePo.getNaireName());
        }
        if (nairePagePo.getStatus() != null) {
            queryWrapper.eq("STATUS", nairePagePo.getStatus());
        }
        queryWrapper.orderByDesc("CREATE_TIME");
        return this.page(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(NaireEntity naireEntity) {
        IBeanUtil.paramVerify(naireEntity, "naireCode");
        boolean isOk = false;
        NaireEntity entity = this.getOne(Wrappers.<NaireEntity>lambdaQuery()
                .eq(NaireEntity::getNaireCode, naireEntity.getNaireCode()));
        if (entity.getStatus() != 0) {
            throw new BusinessException("1008611", "状态为草稿可以删除");
        }
        isOk = this.remove(Wrappers.<NaireEntity>lambdaQuery()
                .eq(NaireEntity::getNaireCode, naireEntity.getNaireCode()));
        return isOk;
    }

    @Override
    public NaireEntity detail(NaireEntity naireEntity) {
        return this.getOne(Wrappers.<NaireEntity>lambdaQuery()
                .eq(NaireEntity::getNaireCode, naireEntity.getNaireCode()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copy(NaireEntity naireEntity) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        NaireEntity entity = this.getOne(Wrappers.<NaireEntity>lambdaQuery()
                .eq(NaireEntity::getNaireCode, naireEntity.getNaireCode()));
        NaireEntity properties = BeanUtil.copyProperties(entity, NaireEntity.class);
        properties.setNaireCode(IdWorker.getIdStr());
        properties.setId(null);
        properties.setStatus(0);
        properties.setCreateTime(LocalDateTime.now());
        properties.setCreatePersonCode(user.getUserCode());
        properties.setCreatePersonName(user.getUserName());
        properties.setUpdatePersonCode(user.getUserCode());
        properties.setUpdatePersonName(user.getUserName());
        properties.setUpdateTime(LocalDateTime.now());
        return this.save(properties);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submit(NaireRecordEntity naireRecordEntity, HttpServletRequest request) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        naireRecordEntity.setRecordCode(IdWorker.getIdStr());
        naireRecordEntity.setCreateTime(LocalDateTime.now());
        naireRecordEntity.setCreatePersonCode(user.getUserCode());
        naireRecordEntity.setCreatePersonName(user.getUserName());
        String ipAddr = IpUtils.getIpAddr(request);
        naireRecordEntity.setIpAddress(ipAddr);
        return naireRecordService.save(naireRecordEntity);
    }

    @Override
    public Page<AnswerPageQueryVo> answerPageQuery(Page page, NairePagePo nairePagePo) {
        Page<AnswerPageQueryVo> pageQueryVoPage = this.getBaseMapper().answerPageQuery(page, nairePagePo);
        if (CollUtil.isNotEmpty(pageQueryVoPage.getRecords())) {
            List<String> naireCodes = pageQueryVoPage.getRecords().stream().map(AnswerPageQueryVo::getNaireCode).collect(Collectors.toList());
            List<NaireRecordEntity> naireRecordEntities = naireRecordService.list(Wrappers.<NaireRecordEntity>lambdaQuery()
                    .in(NaireRecordEntity::getNaireCode, naireCodes));
            if (CollUtil.isNotEmpty(naireRecordEntities)) {
                Map<String, List<NaireRecordEntity>> map = naireRecordEntities.stream().collect(Collectors.groupingBy(NaireRecordEntity::getNaireCode));
                for (AnswerPageQueryVo record : pageQueryVoPage.getRecords()) {
                    if (map.containsKey(record.getNaireCode())) {
                        record.setCollect(map.get(record.getNaireCode()).size());
                    }
                }
            }

        }
        return pageQueryVoPage;
    }

    @Override
    public Page<PageAnswerVo> pageAnswer(Page page, PageAnswerPo pageAnswerPo) {
        Page<PageAnswerVo> pageAnswerVoPage = this.getBaseMapper().pageAnswer(page, pageAnswerPo);
        if (CollUtil.isNotEmpty(pageAnswerVoPage.getRecords())) {
            List<PageAnswerVo> records = pageAnswerVoPage.getRecords();
            Set<String> userCodes = records.stream().map(PageAnswerVo::getCreatePersonCode).collect(Collectors.toSet());
            List<UserInfoVo> userInfoVos = this.getBaseMapper().userCodeInfo(userCodes);
            Map<String, List<UserInfoVo>> listMap = new HashMap<>();
            if (CollUtil.isNotEmpty(userInfoVos)) {
                listMap = userInfoVos.stream().collect(Collectors.groupingBy(UserInfoVo::getUserCode));
            }

            for (PageAnswerVo record : pageAnswerVoPage.getRecords()) {
                StringBuilder deptName = new StringBuilder();
                if (listMap.containsKey(record.getCreatePersonCode())){
                    List<UserInfoVo> infoVos = listMap.get(record.getCreatePersonCode());
                    for (int i1 = 0; i1 < infoVos.size(); i1++) {
                        UserInfoVo userInfoVo = infoVos.get(i1);
                        if (i1 == infoVos.size() - 1) {
                            deptName.append(userInfoVo.getDeptName());
                        } else {
                            deptName.append(userInfoVo.getDeptName()).append("、");
                        }
                        record.setDeptNames(deptName.toString());
                    }
                }
            }
        }
        return pageAnswerVoPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserAnswer(PageAnswerPo pageAnswerPo) {
        NaireRecordEntity naireRecordServiceOne = naireRecordService.getOne(Wrappers.<NaireRecordEntity>lambdaQuery()
                .eq(NaireRecordEntity::getRecordCode, pageAnswerPo.getRecordCode()));
        if (Objects.isNull(naireRecordServiceOne)) {
            throw new BusinessException("1008611", "数据不存在");
        }
        return naireRecordService.remove(Wrappers.<NaireRecordEntity>lambdaQuery()
                .eq(NaireRecordEntity::getRecordCode, naireRecordServiceOne.getRecordCode()));
    }

    @Override
    public ScoreCountVo scoreCount(NaireEntity naireEntity) {
        ScoreCountVo scoreCountVo = new ScoreCountVo();
        int aaa = naireRecordService.count(Wrappers.<NaireRecordEntity>lambdaQuery()
                .eq(NaireRecordEntity::getNaireCode, naireEntity.getNaireCode())
                .lt(NaireRecordEntity::getScore, 60));
        scoreCountVo.setNotQualified(aaa);
        int bbb = naireRecordService.count(Wrappers.<NaireRecordEntity>lambdaQuery()
                .eq(NaireRecordEntity::getNaireCode, naireEntity.getNaireCode())
                .between(NaireRecordEntity::getScore, 60,69.99));
        scoreCountVo.setQualified(bbb);
        int ccc = naireRecordService.count(Wrappers.<NaireRecordEntity>lambdaQuery()
                .eq(NaireRecordEntity::getNaireCode, naireEntity.getNaireCode())
                .between(NaireRecordEntity::getScore, 70,89.99));
        scoreCountVo.setGood(ccc);
        int ddd = naireRecordService.count(Wrappers.<NaireRecordEntity>lambdaQuery()
                .eq(NaireRecordEntity::getNaireCode, naireEntity.getNaireCode())
                .gt(NaireRecordEntity::getScore, 90));
        scoreCountVo.setOutstanding(ddd);
        return scoreCountVo;
    }
}
